#ifndef TARGETCOMMS_H
#define TARGETCOMMS_H

#include <QThread>
#include <QWaitCondition>
#include <QMutex>

#include "registerdef.h"

class QextSerialPort;
class QFile;

class TargetComms : public QThread
{
    Q_OBJECT

public:
    TargetComms(QObject *parent=0);
    ~TargetComms();

    void requestConnect();
    void queueAll();
    void setLogStatus(bool status);
    void dumpLogData();
    QList<RegisterDef>* getRegisterList();

public slots:
    void queueRead(int address);
    void queueWrite(int address, QString value);

signals:
    void connectedToTarget(bool success, QString port);
    void registerUpdated(RegisterDef reg);
    void registerListReady(bool success);
    void targetLost();
    void dumpFinished();
    void errorMessage(QString message);

private:
    bool sendCommand(QString command);
    QByteArray sendRequest(QString request);
    QByteArray targetReadWrite(QString data);
    bool writeRegister(RegisterDef reg, QString value);
    bool readRegister(RegisterDef reg);
    bool readRegisterList();
    bool connectTarget();

    bool setupLogFile(QString fileName);
    void closeLogFile();
    bool getLogData();

    QextSerialPort *target;
    QList<RegisterDef> *registerList;
    QList<RegisterDef> readQueue;
    QList<RegisterDef> writeQueue;
    QString targetPortName;
    QWaitCondition condition;
    QMutex *mutex;
    QMutex *fileMux;
    QFile *logFile;
    QTextStream logData;

    bool logStatus;
    bool gotRegisterList;
    bool targetFound;
    bool tryConnectionAgain;
    bool dumpNeeded;
    bool quit;
    int errorCounter;

protected:
    void run();

};

#endif // TARGETCOMMS_H
